<?php
session_start();
require_once '../includes/functions.php';

// Check if user is admin
if (!is_admin()) {
    redirect('../login.php');
}

include 'includes/header.php';

// Get database connection
require_once '../config/database.php';
$database = new Database();
$db = $database->getConnection();

// Get counts for dashboard
$cars_count = $db->query("SELECT COUNT(*) FROM cars")->fetchColumn();
$available_cars = $db->query("SELECT COUNT(*) FROM cars WHERE status = 'Available'")->fetchColumn();
$reserved_cars = $db->query("SELECT COUNT(*) FROM cars WHERE status = 'Reserved'")->fetchColumn();
$sold_cars = $db->query("SELECT COUNT(*) FROM cars WHERE status = 'Sold'")->fetchColumn();

$pending_inquiries = $db->query("SELECT COUNT(*) FROM inquiries WHERE status = 'New'")->fetchColumn();
$total_users = $db->query("SELECT COUNT(*) FROM users WHERE is_admin = 0")->fetchColumn();
$pending_test_drives = $db->query("SELECT COUNT(*) FROM test_drives WHERE status = 'Pending'")->fetchColumn();

// Get recent inquiries
$recent_inquiries_query = "SELECT i.*, c.title as car_title, u.first_name, u.last_name, u.email, u.phone 
                          FROM inquiries i 
                          LEFT JOIN cars c ON i.car_id = c.id 
                          LEFT JOIN users u ON i.user_id = u.id 
                          ORDER BY i.created_at DESC LIMIT 10";
$recent_inquiries = $db->query($recent_inquiries_query)->fetchAll();
?>

<div class="container-fluid px-4">
    <h1 class="mt-4">Dashboard</h1>
    
    <!-- Statistics Cards -->
    <div class="row mt-4">
        <div class="col-xl-3 col-md-6">
            <div class="card bg-primary text-white mb-4">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h3 class="display-4 mb-0"><?php echo $pending_inquiries; ?></h3>
                            <div class="text-white-50">New Inquiries</div>
                        </div>
                        <i class="fas fa-envelope fa-3x opacity-50"></i>
                    </div>
                </div>
                <div class="card-footer d-flex align-items-center justify-content-between">
                    <a class="small text-white stretched-link" href="inquiries.php" style="text-decoration: none;">View Details</a>
                    <div class="small text-white"><i class="fas fa-angle-right"></i></div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6">
            <div class="card bg-success text-white mb-4">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h3 class="display-4 mb-0"><?php echo $available_cars; ?></h3>
                            <div class="text-white-50">Available Cars</div>
                        </div>
                        <i class="fas fa-car fa-3x opacity-50"></i>
                    </div>
                </div>
                <div class="card-footer d-flex align-items-center justify-content-between">
                    <a class="small text-white stretched-link" href="manage_cars.php" style="text-decoration: none;">View Details</a>
                    <div class="small text-white"><i class="fas fa-angle-right"></i></div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6">
            <div class="card bg-warning text-white mb-4">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h3 class="display-4 mb-0"><?php echo $pending_test_drives; ?></h3>
                            <div class="text-white-50">Pending Test Drives</div>
                        </div>
                        <i class="fas fa-calendar fa-3x opacity-50"></i>
                    </div>
                </div>
                <div class="card-footer d-flex align-items-center justify-content-between">
                    <a class="small text-white stretched-link" href="test_drives.php" style="text-decoration: none;">View Details</a>
                    <div class="small text-white"><i class="fas fa-angle-right"></i></div>
                </div>
            </div>
        </div>
        
        <div class="col-xl-3 col-md-6">
            <div class="card bg-info text-white mb-4">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h3 class="display-4 mb-0"><?php echo $total_users; ?></h3>
                            <div class="text-white-50">Total Users</div>
                        </div>
                        <i class="fas fa-users fa-3x opacity-50"></i>
                    </div>
                </div>
                <div class="card-footer d-flex align-items-center justify-content-between">
                    <a class="small text-white stretched-link" href="users.php" style="text-decoration: none;">View Details</a>
                    <div class="small text-white"><i class="fas fa-angle-right"></i></div>
                </div>
            </div>
        </div>
    </div>

    <!-- After the statistics cards, replace the inquiries section with this -->
    <div class="row">
        <!-- Recent Cars -->
        <div class="col-lg-6 mb-4">
            <div class="card shadow">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <div>
                        <i class="fas fa-car me-1"></i>
                        Recent Cars
                    </div>
                    <a href="manage_cars.php" class="btn btn-primary btn-sm">View All</a>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Image</th>
                                    <th>Title</th>
                                    <th>Price</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $recent_cars_query = "SELECT c.*, b.name as brand_name, m.name as model_name 
                                                    FROM cars c 
                                                    LEFT JOIN brands b ON c.brand_id = b.id 
                                                    LEFT JOIN models m ON c.model_id = m.id 
                                                    ORDER BY c.created_at DESC LIMIT 5";
                                $recent_cars = $db->query($recent_cars_query)->fetchAll();
                                foreach ($recent_cars as $car):
                                ?>
                                <tr>
                                    <td>
                                        <img src="../<?php echo htmlspecialchars($car['main_image']); ?>" 
                                             alt="<?php echo htmlspecialchars($car['title']); ?>"
                                             style="width: 60px; height: 40px; object-fit: cover; border-radius: 4px;">
                                    </td>
                                    <td>
                                        <a href="../car-details.php?id=<?php echo $car['id']; ?>" class="text-decoration-none">
                                            <?php echo htmlspecialchars($car['title']); ?><br>
                                            <small class="text-muted">
                                                <?php echo htmlspecialchars($car['brand_name'] . ' ' . $car['model_name']); ?>
                                            </small>
                                        </a>
                                    </td>
                                    <td>$<?php echo number_format($car['price']); ?></td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            echo $car['status'] === 'Available' ? 'success' : 
                                                ($car['status'] === 'Reserved' ? 'warning' : 'secondary'); 
                                        ?>">
                                            <?php echo $car['status']; ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Inquiries -->
        <div class="col-lg-6 mb-4">
            <div class="card shadow">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <div>
                        <i class="fas fa-envelope me-1"></i>
                        Recent Inquiries
                    </div>
                    <a href="inquiries.php" class="btn btn-primary btn-sm">View All</a>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Car</th>
                                    <th>User</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recent_inquiries as $inquiry): ?>
                                <tr>
                                    <td><?php echo date('Y-m-d', strtotime($inquiry['created_at'])); ?></td>
                                    <td>
                                        <a href="../car-details.php?id=<?php echo $inquiry['car_id']; ?>"  class="text-decoration-none">
                                            <?php echo htmlspecialchars($inquiry['car_title']); ?>
                                        </a>
                                    </td>
                                    <td>
                                        <?php echo htmlspecialchars($inquiry['first_name'] . ' ' . $inquiry['last_name']); ?>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo $inquiry['status'] == 'New' ? 'warning' : 'success'; ?>">
                                            <?php echo $inquiry['status']; ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.card {
    transition: transform 0.2s;
}
.card:hover {
    transform: translateY(-5px);
}
.display-4 {
    font-size: 2.5rem;
    font-weight: 300;
}
.opacity-50 {
    opacity: 0.5;
}
.card-footer {
    background: rgba(0,0,0,0.1);
    border-top: none;
}
.stretched-link::after {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1;
    content: "";
}
</style>

<script>
function updateStatus(inquiryId, status) {
    fetch('inquiries.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `update_status=1&inquiry_id=${inquiryId}&status=${status}`
    })
    .then(response => {
        if (response.ok) {
            location.reload();
        } else {
            alert('Error updating status');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error updating status');
    });
}
</script>

<?php include 'includes/footer.php'; ?> 